﻿namespace PrismEx.SampleApp
{
    using System.Collections.Generic;
    using System.Windows;
    using System.Windows.Controls.Primitives;

    public static class ToggleButtonGroup
    {
        private static Dictionary<string, List<ToggleButton>> groups = new Dictionary<string, List<ToggleButton>>();

        public static string GetGroupName(DependencyObject obj)
        {
            return (string)obj.GetValue(GroupNameProperty);
        }

        public static void SetGroupName(DependencyObject obj, string value)
        {
            obj.SetValue(GroupNameProperty, value);
        }

        public static readonly DependencyProperty GroupNameProperty =
            DependencyProperty.RegisterAttached("GroupName", typeof(string), typeof(ToggleButtonGroup), new UIPropertyMetadata(new PropertyChangedCallback(GroupNameChanged)));

        private static void GroupNameChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var oldValue = e.OldValue as string;
            var newValue = e.NewValue as string;
            var toggleButton = d as ToggleButton;

            if (toggleButton == null) return;

            if (oldValue!= null && groups.ContainsKey(oldValue))
            {
                var group = groups[oldValue];
                group.Remove(toggleButton);

                toggleButton.Checked -= ToggleButtonChecked;
            }

            if (newValue != null)
            {
                if (groups.ContainsKey(newValue))
                {
                    groups[newValue].Add(toggleButton);
                }
                else
                {
                    groups.Add(newValue, new List<ToggleButton> { toggleButton });
                }

                toggleButton.Checked += ToggleButtonChecked;
            }
        }

        static void ToggleButtonChecked(object sender, RoutedEventArgs e)
        {
            var sourceButton = sender as ToggleButton;

            if (sourceButton == null) return;

            var groupName = sourceButton.GetValue(GroupNameProperty) as string;

            if (string.IsNullOrEmpty(groupName)) return;

            if (sourceButton.IsChecked == true)
            {
                foreach (var button in groups[groupName])
                {
                    if (button != sourceButton)
                    {
                        button.IsChecked = false;
                    }
                }
            }
        }
    }
}